﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Mindfor
{
	/// <summary>
	/// Provides functions for serialization.
	/// </summary>
	public static class SerializationExtensions
	{
		/// <summary>
		/// Serializes object using binary formatter and encodes to base64 string.
		/// </summary>
		/// <param name="obj">Object o serialize.</param>
		/// <returns>String if base64 format.</returns>
		public static string SerializeToBase24String(this object obj)
		{
			// serialize to bytes
			IFormatter formatter = new BinaryFormatter();;
			byte[] bytes;
			using (MemoryStream ms = new MemoryStream())
			{
				formatter.Serialize(ms, obj);
				bytes = ms.ToArray();
			}

			// convert to base64 string
			return Convert.ToBase64String(bytes);
		}

		/// <summary>
		/// Deserialzies object from base64 string.
		/// </summary>
		/// <typeparam name="T">Object type to deserialize.</typeparam>
		/// <param name="sourceString">Base64 string to deserialize from.</param>
		/// <returns>Deserialized object.</returns>
		public static T DeserializeFromBase64String<T>(this string sourceString)
		{
			// convert to bytes
			byte[] bytes = Convert.FromBase64String(sourceString);

			// deserialize from bytes
			IFormatter formatter = new BinaryFormatter();
			object obj;
			using (MemoryStream ms = new MemoryStream(bytes))
			{
				obj = formatter.Deserialize(ms);
			}

			// convert to object type
			return (T)obj;
		}
	}
}
